﻿using System;
using System.Data;
using System.Data.OleDb;
using System.Web.Configuration;
using System.Configuration;

/// <summary>
/// Manage database connections
/// </summary>
public class DataBase
{
    /// <summary>
    /// Get predefinded OleDbConnection 
    /// </summary>
    /// <returns>OleDbConnection</returns>
    public static OleDbConnection GetConnection()
    {
        try
        {
            Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("~");
            string connection = rootWebConfig.ConnectionStrings.ConnectionStrings["CadCon"].ConnectionString.ToString();
            return new OleDbConnection(connection);
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }

    /// <summary>
    /// Get custom OleDbConnection 
    /// </summary>
    /// <param name="p_CadCon">Connection string</param>
    /// <returns>OleDbConnection</returns>
    public static OleDbConnection GetConnection(string p_CadCon)
    {
        try
        {
            string connection = p_CadCon;
            return new OleDbConnection(connection);
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }

    /// <summary>
    /// Get a Dataset from a select query
    /// </summary>
    /// <param name="select">select query</param>
    /// <param name="table">target table</param>
    /// <returns>DataSet</returns>
    public static DataSet ds(string select, string table)
    {
        OleDbConnection objConnection = GetConnection();
        OleDbCommand objCommand = new OleDbCommand(select, objConnection);
        OleDbDataAdapter da = new OleDbDataAdapter(objCommand);
        DataSet ds = new DataSet();
        objConnection.Open();

        try
        {
            da.Fill(ds, table);
        }


        catch (OleDbException Ex)
        {
            throw Ex;
        }
        finally
        {
            objConnection.Close();
        }
        return ds;

    }

    /// <summary>
    /// Get Datatable from select query
    /// </summary>
    /// <param name="select">select query</param>
    /// <returns>DataTable</returns>
    public static DataTable dt(string select)
    {
        OleDbConnection objConnection = GetConnection();
        OleDbCommand objCommand = new OleDbCommand(select, objConnection);
        OleDbDataAdapter da = new OleDbDataAdapter(objCommand);
        DataTable dt = new DataTable();
        objConnection.Open();

        try
        {
            da.Fill(dt);
        }
        catch (OleDbException Ex)
        {
            throw Ex;
        }
        finally
        {
            objConnection.Close();
        }
        return dt;
    }

}
